import cgi
import os
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class Link(db.Model):
  title = db.StringProperty()
  url = db.LinkProperty()
  description = db.StringProperty(multiline=True)
  hits = db.IntegerProperty(default=0)
  views = db.IntegerProperty(default=0)
  rating = db.RatingProperty()
  date = db.DateTimeProperty(auto_now_add=True)

class Comment(db.Model):
  comment = db.StringProperty(multiline=True)
  author = db.UserProperty()
  link = db.ReferenceProperty(Link, collection_name='comments')
  approved = db.BooleanProperty(default=False)
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    links_query = Link.all().order('-date')
    links = links_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'links': links,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
    self.response.out.write(template.render(path, template_values))

class ViewAll(webapp.RequestHandler):
  def get(self):
    links_query = Link.all().order('title')
    # FIXME NEED TO FETCH ALL!
    links = links_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'links': links,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
    self.response.out.write(template.render(path, template_values))

class ViewPopular(webapp.RequestHandler):
  def get(self):
    links_query = Link.all().order('-hits')
    links = links_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'links': links,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
    self.response.out.write(template.render(path, template_values))

class ViewLink(webapp.RequestHandler):
  def get(self):
    link = db.get(self.request.get('key'))
    
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
    
    template_values = {
      'link': link,
      'url': url,
      'url_linktext': url_linktext,
    }

    link.views += 1
    link.put()

    path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
    self.response.out.write(template.render(path, template_values))


class AddLink(webapp.RequestHandler):
  def post(self):
    link = Link()
    link.title = self.request.get('title')
    link.url = self.request.get('url')
    link.description = self.request.get('description')
    link.put()
    self.redirect('/')

class PostComment(webapp.RequestHandler):
  def post(self):
    comment = Comment()

    if users.get_current_user():
      comment.author = users.get_current_user()

    comment.comment = self.request.get('comment')
    link = db.get(self.request.get('key'))
    comment.link = link
    comment.put()

    self.redirect('/view?key=' + self.request.get('key'))

class Visit(webapp.RequestHandler):
  def get(self):
    link = db.get(self.request.get('key'))
    link.hits += 1
    link.put()
    self.redirect(link.url)

class AdminPage(webapp.RequestHandler):
  def get(self):
    if users.is_current_user_admin():
      path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      
      template_values =  {
        'url': url,
        'url_linktext': url_linktext,
        }
      
      self.response.out.write(template.render(path, template_values))
    else:
      self.redirect('/')
      
class InfoPage(webapp.RequestHandler):
  def get(self):
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
    
    template_values = {
      'url': url,
      'url_linktext': url_linktext,
      }
    
    path = os.path.join(os.path.dirname(__file__), 'templates/info.html')
    self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication(
    [('/', MainPage),
     ('/_admin', AdminPage),
     ('/add_link', AddLink),
     ('/all', ViewAll),
     ('/info', InfoPage),
     ('/popular', ViewPopular),
     ('/post_comment', PostComment),
     ('/view', ViewLink),
     ('/visit', Visit)],
    debug=True)
  
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
